Imports System
Imports System.Collections.Generic
Imports System.Text
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data.Common
Imports ViewStateEliminator_VB.ViewStateEliminator.Configuration

Namespace ViewStateEliminator.Data
    Public Class ViewStateSQLStorage
        Implements IViewstateStorage

        Private _db As Database
        Private _cmd As DbCommand
        Public Sub New()
            Dim config As ViewStateConfiguration = CType(System.Configuration.ConfigurationManager.GetSection("ViewStateConfiguration"), ViewStateConfiguration)
            If (config.defaultDatabase.Trim().Length = 0) Then
                _db = DatabaseFactory.CreateDatabase()
            Else
                _db = DatabaseFactory.CreateDatabase(System.Configuration.ConfigurationManager.ConnectionStrings(config.defaultDatabase).Name)

            End If
        End Sub

        Public Sub Add(ByVal viewstateItem As System.Collections.Generic.KeyValuePair(Of Object, String)) Implements IViewstateStorage.Add
            _cmd = _db.GetStoredProcCommand("ViewStateSource_ADD")
            _db.AddInParameter(_cmd, "viewstateKey", System.Data.DbType.String, viewstateItem.Key.ToString())
            _db.AddInParameter(_cmd, "viewstate", System.Data.DbType.String, viewstateItem.Value.ToString())
            _db.AddInParameter(_cmd, "ip", System.Data.DbType.String, System.Web.HttpContext.Current.Request.UserHostAddress.ToString())

            _db.ExecuteNonQuery(_cmd)
        End Sub

        Public Function [Get](ByVal key As Object) As System.Collections.Generic.KeyValuePair(Of Object, String) Implements IViewstateStorage.Get
            _cmd = _db.GetStoredProcCommand("ViewStateSource_GET")
            _db.AddInParameter(_cmd, "viewstateKey", System.Data.DbType.String, key.ToString())
            Dim retItem As System.Collections.Generic.KeyValuePair(Of Object, String) = New System.Collections.Generic.KeyValuePair(Of Object, String)(CType(key, Object), CStr(_db.ExecuteScalar(_cmd)))
            Return retItem
        End Function

        Public Sub Remove(ByVal key As Object) Implements IViewstateStorage.Remove


        End Sub
    End Class
End Namespace
